import 'dart:io';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_shipper/Main/CustomerService/ProblemDetails.dart';
import 'package:sph_shipper/Main/MyWallet/MyWallet.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/ShowDialog.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../l10n/messages.dart';
import '../Insure/Insure.dart';
import '../ServiceHall/Feedback.dart';
import 'ServiceDataModification.dart';
import 'TransactionDisputes.dart';
import 'package:platform/platform.dart';
class CustomerServiceMain extends StatefulWidget {
  const CustomerServiceMain({super.key});

  @override
  State<CustomerServiceMain> createState() => _CustomerServiceMainState();
}

class _CustomerServiceMainState extends State<CustomerServiceMain> {

  int qaType=0;
  List qaTitleList=[];
  List pIdList=[];
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getPageAction();
    ///initState 中添加监听，记得销毁
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });
  }

  void getPageAction(){
    NoLoadinggetApiManager.getData(
      context,
      "api/system/dev/dict/list",
      {'category':'BIZ','parentId':qaType==0?"1807656747907014658":qaType==1?"1807656919609237505":qaType==2?"1807657061380907010":"1807657181224755202"},
          (responseData)  {
        setState(() {
          qaTitleList = responseData['data'].map((item) => item['dictLabel']).toList();
          pIdList=responseData['data'];
        });
      },
    );
  }

  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        // 权限被拒绝，但用户可以再次授权
        showCallPhoneFirstDialog(context);
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
        appBar: AppBar(
        backgroundColor: MyColors.themeColor,
        centerTitle: true,
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios, color: Colors.white),
            onPressed: () => Navigator.of(context).pop(),
          ),
        title: Text(messages['客户服务'],style: TextStyle(color: Colors.white,fontWeight: FontWeight.w300,fontSize: 16.sp),),
        ),
      body: Column(
        children: [
          Expanded(
              child: Container(
                padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [MyColors.themeColor,MyColors.backgreyColor],
                    begin: Alignment.topCenter,
                    end: Alignment(0.0, -0.55),
                  ),
                ),
                child: ListView(
                  children: [
                    Text("Hi，欢迎来到这里\n看看我们有什么能帮您的？",style: TextStyle(color: Colors.white,fontSize: 16.sp,fontWeight: FontWeight.w600),),
                    SizedBox(height: 8.h,),
                    // Container(
                    //   height: 35.h,
                    //   decoration: BoxDecoration(
                    //     color: Colors.white,
                    //     borderRadius: BorderRadius.all(Radius.circular(20)),
                    //
                    //   ),
                    //   child:  BrnSearchText(
                    //     focusNode: focusNode,
                    //     controller: textController,
                    //     searchController: scontroller..isActionShow = false,
                    //     innerColor:Colors.white,
                    //     borderRadius:BorderRadius.all(const Radius.circular(30.0)),
                    //     hintText:"搜索问题",
                    //     onTextClear: () {
                    //       debugPrint('sss');
                    //       return false;
                    //     },
                    //
                    //     onActionTap: () {
                    //       scontroller.isClearShow = false;
                    //       scontroller.isActionShow = false;
                    //       focusNode.unfocus();
                    //       BrnToast.show('取消', context);
                    //     },
                    //     onTextCommit: (text) {
                    //       BrnToast.show('提交内容 : $text', context);
                    //     },
                    //     onTextChange: (text) {
                    //       BrnToast.show('输入内容 : $text', context);
                    //     },
                    //   ),
                    // ),
                    // SizedBox(height: 8.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        GestureDetector(
                          child:  Column(
                            children: [
                              Text("猜你想问",style: TextStyle (fontWeight:qaType==0? FontWeight.w600:FontWeight.w300,color:Colors.black,fontSize: qaType==0?14.sp:14.sp),),
                              SizedBox(height: 6.h,),
                              Container(height: 2.h,width: 27.w,color:qaType==0?Color.fromRGBO(231, 112, 27, 0.85) : Colors.white.withOpacity(0.0),),
                            ],
                          ),
                          onTap: (){
                            setState(() {
                              qaType=0;
                              getPageAction();
                            });
                          },
                        ),

                        GestureDetector(
                          child: Column(
                            children: [
                              Text("交易纠纷",style: TextStyle (fontWeight:qaType==1? FontWeight.w600:FontWeight.w300,color:Colors.black,fontSize: qaType==1?14.sp:14.sp),),
                              SizedBox(height: 6.h,),
                              Container(height: 2.h,width: 27.w,color:qaType==1?Color.fromRGBO(231, 112, 27, 0.85) : Colors.white.withOpacity(0.0),),
                            ],
                          ),
                          onTap: (){
                            setState(() {
                              qaType=1;
                              getPageAction();
                            });
                          },
                        ),
                        GestureDetector(
                          child:      Column(
                            children: [
                              Text("修改资料",style: TextStyle (fontWeight:qaType==2? FontWeight.w600:FontWeight.w300,color:Colors.black,fontSize: qaType==2?14.sp:14.sp),),
                              SizedBox(height: 6.h,),
                              Container(height: 2.h,width: 27.w,color:qaType==2?Color.fromRGBO(231, 112, 27, 0.85) : Colors.white.withOpacity(0.0),),
                            ],
                          ),
                          onTap: (){
                            setState(() {
                              qaType=2;
                              getPageAction();
                            });
                          },
                        ),
                        GestureDetector(
                          child:   Column(
                            children: [
                              Text("运输订单",style: TextStyle (fontWeight:qaType==3? FontWeight.w600:FontWeight.w300,color:Colors.black,fontSize: qaType==3?14.sp:14.sp),),
                              SizedBox(height: 6.h,),
                              Container(height: 2.h,width: 27.w,color:qaType==3?Color.fromRGBO(231, 112, 27, 0.85) : Colors.white.withOpacity(0.0),),
                            ],
                          ),
                          onTap: (){
                            setState(() {
                              qaType=3;
                              getPageAction();
                            });
                          },
                        ),

                      ],
                    ),
                    Container(
                      height: qaTitleList.length *38.h,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                      child: ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap:false,
                        itemCount: qaTitleList.length,
                        itemBuilder: (BuildContext context, int index) {
                          return Container(
                            padding: EdgeInsets.only(left: 8.w,right: 8.w,),
                            child:GestureDetector(
                              child:   Column(
                                children: [
                                  SizedBox(height: 10.h,),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(qaTitleList[index],style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                      Icon(Icons.arrow_forward_ios,color: MyColors.hintColor,size: 14,),
                                    ],
                                  ),
                                  SizedBox(height: 10.h,),
                                  Container(
                                    height: 1.h,
                                    color: MyColors.backgreyColor,
                                  ),
                                ],
                              ),
                              onTap: (){

                                Navigator.push( context, FadeRoute(page:ProblemDetails(dataMap: pIdList[index],)));
                              },
                            ),
                          );
                        },
                      ),
                    ),
                    SizedBox(height: 8.h,),
                    Text(" "+"快捷服务",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
                    SizedBox(height: 8.h,),
                    Container(
                      padding:EdgeInsets.only(left: 20.w,right: 20.w,top:15.h,bottom: 15.h),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              // BrnIconButton(
                              //     name: messages["交易纠纷"],
                              //     style: TextStyle(
                              //       fontSize: 13.sp,
                              //       color: Colors.black,
                              //     ),
                              //     direction: Direction.bottom,
                              //     padding: 4.h,
                              //     iconHeight: 26.h,
                              //     iconWidth: 26.w,
                              //     iconWidget: Image.asset("lib/Images/PersonCenter/交易纠纷icon.png"),
                              //     onTap: () {
                              //       Navigator.push( context, FadeRoute(page:TransactionDisputes()));
                              //     }),
                              BrnIconButton(
                                  name: messages["钱包业务"],
                                  style: TextStyle(
                                    fontSize: 13.sp,
                                    color: Colors.black,
                                  ),
                                  direction: Direction.bottom,
                                  padding: 4.h,
                                  iconHeight: 26.h,
                                  iconWidth: 26.w,
                                  iconWidget: Image.asset("lib/Images/PersonCenter/钱包业务icon.png"),
                                  onTap: () {
                                    Navigator.push( context, FadeRoute(page:MyWallet()));

                                  }),
                              BrnIconButton(
                                  name: messages["资料修改"],
                                  style: TextStyle(
                                    fontSize: 13.sp,
                                    color: Colors.black,
                                  ),
                                  direction: Direction.bottom,
                                  padding: 4.h,
                                  iconHeight: 26.h,
                                  iconWidth: 26.w,
                                  iconWidget: Image.asset("lib/Images/PersonCenter/资料修改icon.png"),
                                  onTap: () {
                                    Navigator.push( context, FadeRoute(page:ServiceDataModification()));
                                  }),
                              BrnIconButton(
                                  name: messages["意见建议"],
                                  style: TextStyle(
                                    fontSize: 13.sp,
                                    color: Colors.black,
                                  ),
                                  direction: Direction.bottom,
                                  padding: 4.h,
                                  iconHeight: 26.h,
                                  iconWidth: 26.w,
                                  iconWidget: Image.asset("lib/Images/PersonCenter/意见建议icon.png"),
                                  onTap: () {
                                    Navigator.push( context, FadeRoute(page:FeedBack()));
                                  }),
                            ],
                          ),
                          SizedBox(height: 8.h,),
                          // Row(
                          //   mainAxisAlignment: MainAxisAlignment.start,
                          //   children: [
                          //     BrnIconButton(
                          //         name: messages["保险问题"],
                          //         style: TextStyle(
                          //           fontSize: 13.sp,
                          //           color: Colors.black,
                          //         ),
                          //         direction: Direction.bottom,
                          //         padding: 4.h,
                          //         iconHeight: 26.h,
                          //         iconWidth: 26.w,
                          //         iconWidget: Image.asset("lib/Images/PersonCenter/保险问题icon.png"),
                          //         onTap: () {
                          //           Navigator.push( context, FadeRoute(page:Insure()));
                          //
                          //         }),
                          //
                          //   ],
                          // ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
          ),
          Container(
            height: 100.h,
            width: screenSize.width,
            color: Colors.white,
            padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 10.h,bottom: 40.h),
            child: Row(
              children: [
                // Container(
                //   child:  BrnIconButton(
                //       name: '服务进度',
                //       style: TextStyle(
                //         fontSize: 12.sp,
                //         color: Colors.black,
                //       ),
                //       direction: Direction.bottom,
                //       padding: 2.h,
                //       iconHeight: 24.h,
                //       iconWidth: 24.w,
                //       iconWidget: Image.asset("lib/Images/PersonCenter/服务进度icon.png"),
                //       onTap: () {
                //         // Navigator.push(context,
                //         //     MaterialPageRoute(builder: (context) {
                //         //       return SettingList(
                //         //       );
                //         //     }));
                //       }),
                // ),
                Container(
                  margin: EdgeInsets.only(left: 15.w,right: 15.w),
                  width: screenSize.width-50.w,
                  height: 35.h,
                  child:  BrnSmallMainButton(
                    title: '电话客服',
                    bgColor: MyColors.themeColor,
                    fontSize: 16.sp,
                    radius: 30,
                    onTap: () {
                      _makePhoneCall("0574-86761267");
                    },
                  ),
                ),
              ],
            ),
          )
        ],
      ),


    );
  }
}
